﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;

public partial class UpBaseData : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userName"] == null || Session["roleID"] == null)
        {
            Response.Redirect("Login.aspx");
            Response.End();
        } 
        if (!Page.IsPostBack)
        {            
            lblUserName.Text =BasicClass.GetTrueNameByUserName(Session["userName"].ToString());
            string DataType = Request.QueryString["type"].ToString().Trim();
            lblDataType.Text = DataType;
            BindToDdlFlowModel(DataType);
            BindToDdlSubDataType();            
            DisplayAccessMan();
            FileUploadDaTa.Attributes.Add("onchange", "getfilename(this.value)");
            BindToMenu(DataType);
            txtWriteDate.Value = DateTime.Now.ToShortDateString();
            if (Session["roleId"].ToString() == "1")
            {
                chkAddOldFile.Visible = true;
            }
            else
            {
                chkAddOldFile.Visible = false;
            }
 
        }

    }
    protected void BindToMenu(string dataType)
    {
        BasicClass BC = new BasicClass();
        Hashtable menuHt = BC.GetArrayIndexByShortMark();

        int i =Convert.ToInt32(menuHt[dataType].ToString());
        string[,] dataMenu = BC.GetUpDataMenu();
        lblHead.Text = dataMenu[i, 0].ToString();
        lblWriter.Text = dataMenu[i, 1].ToString();
        lblMainFile.Text = dataMenu[i, 2].ToString();
        lblAttachFile.Text = dataMenu[i, 3].ToString();
        lblTitle.Text = dataMenu[i, 4].ToString();
        lblFlowModel.Text = dataMenu[i, 5].ToString();
        lblSendTo.Text = dataMenu[i, 6].ToString();
        lblWriteDate.Text = dataMenu[i, 7].ToString();
        lblBrief.Text = dataMenu[i, 8].ToString();
 
    }
    private void BindToDdlFlowModel(string tempDataType)
    {
        string sqlString = "select * from LCMINFO inner join FLOWTYPE on LCMINFO.FLOWTYPEID=FLOWTYPE.FLOWTYPEID where FLOWTYPE.SHORTMARK='" + tempDataType + "'";
        DBOperation DBO = new DBOperation();
        SqlDataReader sdr = DBO.GetDataReader(sqlString);        
        ddlFlowModel.DataSource = sdr;
        ddlFlowModel.DataValueField = "FLOWMID";
        ddlFlowModel.DataTextField = "FLOWMNAME";
        ddlFlowModel.DataBind();
        if (ddlFlowModel.Items.Count == 0)
        {
            if (Session["roleID"].ToString() == "1")
            {
                Response.Write("<script langeuage='javascript'>alert('该资料类型没有可用的审核流程模板，请先添加！');location.href='FlowSet.aspx';</script>");
                Response.End();
            }
            else
            {
                Response.Write("<script langeuage='javascript'>alert('该资料类型没有可用的审核流程模板，请先联系管理员添加后再提交！');location.href='MessageInfo.aspx';</script>");
                Response.End();
 
            }
        }
        sdr.Close();
    }
    //绑定数据到资料二级分类
    private void BindToDdlSubDataType()
    {
        string sqlString = "select * from FLOWSUBTYPE where PARENTTYPEID=1";
        DBOperation DBO = new DBOperation();
        SqlDataReader sdr = DBO.GetDataReader(sqlString); 
        ddlSubDataType.DataSource = sdr;
        ddlSubDataType.DataValueField = "FLOWSUBTYPEID";
        ddlSubDataType.DataTextField = "SUBTYPENAME";
        ddlSubDataType.DataBind();
        sdr.Close();
    }    
    //显示接收者
    private void DisplayAccessMan()
    {
        if (ddlFlowModel.SelectedValue.ToString() != "")
        {
            int flowMID = Convert.ToInt32(ddlFlowModel.SelectedValue.ToString());
            string sqlString = "select top 1 * from LCBZMINFO where FLOWMID=" + flowMID.ToString() + " order by SEQ ASC";
            DBOperation DBO = new DBOperation();
            SqlDataReader sdr = DBO.GetDataReader(sqlString);
            BasicClass BC = new BasicClass();
            while (sdr.Read())
            {
                lblDep.Text = BC.GetDepNameByUserName(sdr["USERIDLIST"].ToString());
                lblName.Text = BasicClass.GetTrueNameByUserName(sdr["USERIDLIST"].ToString());
            }
            sdr.Close();
        }
    }
        
    //自动显示送交单位和第一审核人
    protected void ddlFlowModel_SelectedIndexChanged(object sender, EventArgs e)
    {
        FileUploadDaTa.EnableViewState = true;
        DisplayAccessMan();
        
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {      
        
        if (UpMainFile())
        {
            if(UpAttachFiles())
            {                
                string WriteDateString = txtWriteDate.Value.Trim();
                DateTime WriteDate = Convert.ToDateTime(WriteDateString);
                string FilesPath = txtUpFileStatus.Text;
                DataOperation data = new DataOperation();
                data.Title = BasicClass.HtmlEncode(txtTitle.Text);
                data.SubTitle = txtSubTitle.Text;                
                data.UserName = Session["userName"].ToString();
                data.WriteDate = WriteDate;
                data.FilesPath = FilesPath;
                data.FlowMID = Convert.ToInt32(ddlFlowModel.SelectedValue);                
                data.DataType = lblDataType.Text.Trim();
                data.Brief = BasicClass.HtmlEncode(txtDataBrief.Text);
                data.AttachFiles = txtFilePath.Text;
                if (chkAddOldFile.Checked)
                {
                    data.FlowStatus = "1";
                }
                else
                {
                    data.FlowStatus = "0";
                }
                if (data.AddData())
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('资料上传成功!');location.href='UpBaseData.aspx?type="+lblDataType.Text.Trim()+"';", true);                   

                }
            }
        }
        

    }
    //上传附件,上传成功则返回文件路径
    private string UpDataFile()
    {
        string fullFileName = FileUploadDaTa.PostedFile.FileName.ToString().Trim();
        string type = fullFileName.Substring(fullFileName.LastIndexOf(".") + 1).ToLower();
        string SaveFilename = fullFileName.Substring(fullFileName.LastIndexOf("\\") + 1);
        if (type == "exe")
        //if (type.ToString() != "jpg" && type != "jpeg" && type != "bmp" && type != "gif" && type != "png")
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('文件格式不对！');", true);            
        }
        else
        {
            DataOperation DBO = new DataOperation();
            Hashtable Tableprefix = BasicClass.GetTabPrefixAndDataIDHashTab();
            string fileDir = Tableprefix[lblDataType.Text.Trim()].ToString();
            string FilePath = DBO.CheckDirectory(fileDir);
            string DataFilePath = FilePath + "\\" + SaveFilename;
            if (File.Exists(Server.MapPath("files") + DataFilePath))
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('主文件重名，请重命名主文件后再上传！');", true);                
                return null;
            }
            else
            {
                FileUploadDaTa.PostedFile.SaveAs(Server.MapPath("files") + DataFilePath);
                return DataFilePath;
            }

        }
        return null;
    }
    protected Boolean UpMainFile()
    {
        bool success = false;
        if (CheckFiles())
        {
            string UpFilePath = FileUploadDaTa.PostedFile.FileName.ToString().Trim();            
            if (UpFilePath != "")
            {
                try
                {
                    string filePath = UpDataFile();
                    if (filePath != null)
                    {
                        string FileName = UpFilePath.Substring(UpFilePath.LastIndexOf("\\") + 1);
                        string FileNameShort = FileName.Substring(0, FileName.LastIndexOf("."));
                        txtUpFileStatus.Text = filePath;
                        txtSubTitle.Text = FileName;
                        success = true;
                    }
                    else
                    {
                        success = false;
                    }

                }
                catch
                {
                    success = false;
                }
            }
        }
        return success;
    }
    protected Boolean UpAttachFiles()
    {
        lblFailMsg.Text = "<br/>";
        bool success = true;        
        DataOperation DBO = new DataOperation();
        Hashtable Tableprefix = BasicClass.GetTabPrefixAndDataIDHashTab();
        string fileDir = Tableprefix[lblDataType.Text.Trim()].ToString();
        string FilePath = DBO.CheckDirectory(fileDir);
        for (int i = 0; i < Request.Files.Count; i++)
        {
            string filePath = Request.Files[i].FileName;
            //判断上传文件框里是否有文件
            if (filePath != "")
            {
                string shortFileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);
                string DataFilePath = FilePath + "\\" + shortFileName;
                if (shortFileName != txtSubTitle.Text.ToString().Trim())
                {
                    if (File.Exists(Server.MapPath("files") + DataFilePath))
                    {
                        lblFailMsg.Text = lblFailMsg.Text + "<font color='red'>存在同名文件：" + shortFileName + "</font>;请更名后再上传该文件。<br/>";
                        success = false;
                    }
                    else
                    {                        
                        Request.Files[i].SaveAs(Server.MapPath("files") + DataFilePath);
                        txtFilePath.Text += DataFilePath + ",";                        
                    }
                }
            }
        }
        return success;
    }
    /// <summary>
    /// 检查上传的文件中是否有与服务器中文件同名的文件
    /// </summary>
    /// <returns>有则返回false，否则返回true</returns>
    protected Boolean CheckFiles()
    {
        lblFailMsg.Text = "<br/>";
        DataOperation DBO = new DataOperation();
        Hashtable Tableprefix = BasicClass.GetTabPrefixAndDataIDHashTab();
        string fileDir = Tableprefix[lblDataType.Text.Trim()].ToString();
        string FilePath = DBO.CheckDirectory(fileDir);
        bool fileCheck = true;
        string errorMsg = "以下文件服务器中存在同名文件：";
        for (int j = 0; j < Request.Files.Count; j++)
        {
            string filePath = Request.Files[j].FileName;
            //判断上传文件框里是否有文件
            if (filePath != "")
            {
                string shortFileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);
                string DataFilePath = FilePath + "\\" + shortFileName;
                if (File.Exists(Server.MapPath("files") + DataFilePath))
                {
                    lblFailMsg.Text = lblFailMsg.Text + "<font color='red'>存在同名文件：" + shortFileName + "</font>;请更名后再添加该文件。<br/>";
                    errorMsg += shortFileName + ",";
                    fileCheck = false;
                }
            }
        }
        if (!fileCheck)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('" + errorMsg + "');", true);
        }
        return fileCheck;
    }

    protected void btnUpFile_Click(object sender, EventArgs e)
    {      
        

    }
    protected void txtReset_Click(object sender, EventArgs e)
    {
        Response.Redirect("MessageInfo.aspx");

    }
}
